<?php

namespace App\Http\Middleware;

use App\Model\Users;
use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!in_array($request->path(), $this->whiteList())) {
            if ($token = $request->header('x-token', '')) {
                $users = Users::findByToken($token);
                if (empty($users)) {
                    return response()->json(['code' => 50014, 'data' => [], 'message' => 'TOKEN 失效，请重新登录']);
                }

                $action = Route::currentRouteAction();
                $index = strrpos($action, '\\');
                $action = substr($action, $index + 1);
                $permission = strtolower(str_replace('Controller@', '_', $action));
                try {
                    if (!($res = $users->hasPermissionTo($permission))) {
                        return response()->json(['code' => 50002, 'data' => [], 'message' => '无权操作']);
                    }
                } catch (\Exception $e) {
                    return $next($request);
                }

            } else {
                return response()->json(['code' => 50014, 'data' => [], 'message' => 'TOKEN 失效，请重新登录。']);
            }
        }
        return $next($request);
    }

    /**
     * 白名单
     * @return array
     */
    private function whiteList()
    {
        return [
            'api/user/getPass',
            'api/user/login',
            'api/file/upload',
            'api/check/records',
            'api/accounts/tt',
            'api/cost_statistics',
            'api/user_active_statistics',
            'api/income_statistics',
            'api/diamond_output',
            'api/diamond_consume_statistics',
            'api/kk_balance_statistics',
            'api/channel_statistics',
            'api/pearl_output',
            'api/pearl_consume_statistics',
            'api/financeCabinPearlStream',
            'api/financeRoomWealthStream',
            'api/systems/voice/logs',
            'api/getRYChatLogs',
            'api/xiazai',
            'api/test',
            'api/file/uploadNew',
        ];
    }
}
